package pers.youqu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.youqu.common.constants.MQConstants;
import pers.youqu.common.exception.YqException;
import pers.youqu.common.utils.EmptyUtil;
import pers.youqu.common.utils.RegexUtils;
import pers.youqu.user.dto.UserDTO;
import pers.youqu.user.mapper.UserMapper;
import pers.youqu.user.po.User;
import pers.youqu.user.service.UserService;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final String CODE_KEY_PREFIX = "user:code:phone:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Boolean isExists(String data, Integer type) {

        if(type != 1 && type != 2){
            throw new YqException(400, "请求参数有误");
        }

        return query()
                .eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count() == 1;
    }

    @Override
    public void sendCode(String phone) {

        if (!RegexUtils.isPhone(phone)) {
            throw new YqException(400, "请求参数有误");
        }

        String code = RandomStringUtils.randomNumeric(6);

        // 保存到redis设置失效时间
        redisTemplate.opsForValue().set(CODE_KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);

        // 发送到mq，发短信服务监听发短信
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
//        amqpTemplate.convertAndSend(MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME, MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY, msg);
    }

    @Override
    @Transactional
    public void registerUser(User user, String code) {

        // 获取验证码校验
        String cacheCode = redisTemplate.opsForValue().get(CODE_KEY_PREFIX + user.getPhone());
        if (EmptyUtil.isNullOrEmpty(cacheCode)) {
            throw new YqException(400, "验证码过期");
        }
        if (code == null || !code.equals(cacheCode)) {
            throw new YqException(400, "验证码错误");
        }
        // 加盐加密后替换密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        save(user);
    }

    @Override
    public UserDTO findUserByUsernameAndPassword(String username, String password) {

        User user = query().eq("username", username).one();
        if (EmptyUtil.isNullOrEmpty(user)) {
            throw new YqException(400, "用户名有问题");
        }

        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new YqException(400, "用户名或密码错误");
        }

        return new UserDTO(user);
    }


}